< previous page page_246 next page >

Page 246
The bouncing object programs presented in Chapter 8 all perform a simulation of moving objects. They use a simple set of physical laws to determine how each object moves over time. In these programs the laws of movement are:
Objects have constant velocities with X and Y components Vx and Vy.
If an object is at position (Cx, Cy) at a given time, in the next frame, it has position (Cx + Vx, Cy + Vy).
If an object touches the left or right edge of the drawing area, it bounces back, reversing the direction of its X velocity component.
If an object touches the top or bottom edge of the drawing area, it bounces back, reversing the direction of its Y velocity component.
Program Stocks2 also generates its data using rules. Its rules make it select random stock values with some bounding operations to ensure that the values do not vary too quickly.
Simple planetary motion is governed by the physical laws:
e10a6a0a59f035e870d90cca05b85fce.gif
F = m1 * m2 / d2

F = m * a
The first equation gives the gravitational force that two objects exert on each other. In this equation, m1 and m2 are the masses of two objects, and d is the distance between them.
You can rewrite the second equation as a = F/m. In other words, if you apply a force F to an object of mass m, it accelerates by amount a.
Using these two equations, you can build a simulation of planetary motion. The program must keep track of each object's mass, position, and velocity.
The main difference between this simulation and the previous bouncing ball programs is that this program calculates acceleration. For each frame, the program computes the force each object exerts on the others. It does this using the equation F = m1 * m2/d2 for each pair of objects.
Once it has a force acting on an object, the program uses the second equation to compute the acceleration of the object due to that force. If the force F is acting on an object with mass m, its acceleration is a = F/m.
Acceleration is the rate of change in the velocity of an object. The acceleration due to another object is in the direction of the other object. To find the X and Y components of the acceleration, the program multiplies the acceleration by the X and Y components of the vector from one object to the other. In other words, if dx and dy are the distances between the two objects in the X and Y directions, and d = Sqr(dx * dx + dy * dy) is the distance between the objects, the components of the acceleration are:
e10a6a0a59f035e870d90cca05b85fce.gif
X component = dx / d * acceleration
Y component = dy / d * acceleration

 
< previous page page_246 next page >